<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { DataViewInstance, fmtDate, hBtns, hStatusTag, openDialog, statusSelect, TableColumnProps, MenuItem, request } from '../../../utils';
import { Plus, Sort } from '@element-plus/icons-vue';

const viewRef = ref<DataViewInstance>()

const columns = [
  { label: '菜单名称', prop: 'menuName', minWidth: 170 },
  { label: '图标', prop: 'icon', minWidth: 60 },
  { label: '排序', prop: 'sort', minWidth: 60 },
  { label: '权限标识', prop: 'perm', minWidth: 150 },
  { label: '组件路径', prop: 'component', minWidth: 170 },
  {
    label: '状态',
    minWidth: 80,
    render: (_, { row }) => hStatusTag(row.status)
  },
  {
    label: '创建时间',
    minWidth: 170,
    render: (h, { row }) => h('span', fmtDate(row.createdAt))
  },
  {
    label: '操作',
    width: 150,
    fixed: 'right',
    render: (_, { row }) => {
      return hBtns([
        { label: '修改', onClick: onEdit.bind(null, row, true) },
        { label: '新增', onClick: onEdit.bind(null, row, false) },
        { label: '删除', type: 'danger', onClick: onDelete.bind(null, row) }
      ])
    }
  }
] as TableColumnProps<MenuItem>[]

const fetchAction = async (params: any) => {
  return request('/menu/list', { params })
}

const onEdit = (row?: MenuItem, isEdit?: boolean) => {
  openDialog({
    vm: () => import('./edit.vue'),
    vmProps: { row, isEdit },
    dialogProps: {
      title: isEdit ? '编辑' : '新增',
      onSubmitted: () => viewRef.value?.getData()
    }
  })
}

const onDelete = (row: MenuItem) => {
  viewRef.value?.deleteRows(
    () => request.post('/dept/delete', { id: row._id })
  )
}

const expandAll = ref(true)

const onToggleExpand = () => {
  expandAll.value = !expandAll.value
}

onMounted(() => {
  viewRef.value?.getData()
})
</script>

<template>
  <UiDataView
    ref="viewRef"
    row-key="_id"
    :expand-all="expandAll"
    :columns="columns"
    :fetch-action="fetchAction"
    :config="{ pager: false }">
    <template #form="{ form, onSearch }">
      <ElFormItem label="菜单名称">
        <ElInput placeholder="请输入菜单名称" v-model="(form as MenuItem).menuName" @keyup.enter="onSearch" />
      </ElFormItem>
      <ElFormItem label="状态">
        <ElSelect placeholder="请选择状态"clearable v-model="(form as MenuItem).status" @change="onSearch">
          <ElOption v-for="_ in statusSelect" :key="_.value" v-bind="_" />
        </ElSelect>
      </ElFormItem>
    </template>
    <template #actions>
      <ElButton plain type="primary" :icon="Plus" @click="onEdit()">新增</ElButton>
      <ElButton plain type="info" :icon="Sort" @click="onToggleExpand()">展开/折叠</ElButton>
    </template>
  </UiDataView>
</template>
